﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using dal.cgm_production_dao;
using Newtonsoft.Json;
using utils;

namespace reader_outerbox_label_printing
{
    public partial class Form1 : Form
    {
        private System.Windows.Forms.Timer validationTimer;

        public Form1()
        {
            InitializeComponent();
            // 初始化计时器
            validationTimer = new System.Windows.Forms.Timer();
            validationTimer.Interval = 500; // 延迟500毫秒
            validationTimer.Tick += new EventHandler(ValidationTimer_Tick);
            versionLabel.Text = "v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

        }

        /// <summary>
        /// dmText_TextChanged
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dmText_TextChanged(object sender, EventArgs e)
        {
            // 每次文本改变时重置计时器
            validationTimer.Stop();
            validationTimer.Start();
        }

       

        private  void ValidationTimer_Tick(object sender, EventArgs e)
        {
            validationTimer.Stop(); // 停止计时器
            //dmText格式: (01)18500441188781(11)241010(10)16T3123456(21)24081448S

            string errorMsg = "彩盒码格式校验失败";
            int indexLen = 4;
            int gtinLen = 14;
            int dateLen = 6;
            int lotLen = 10;
            int snLen = 9;
            string gtinTag = "(01)";
            string productionDateTag = "(11)";
            string lotTag = "(10)";
            string snTag = "(21)";

            int len = indexLen + gtinLen + indexLen + dateLen + indexLen + lotLen + indexLen + snLen;
            string dmCode = dmText.Text;
            label2.Text = string.Empty;

            // 截取后七个字符
            if (dmCode.Length < len)
            {
                HandleError(errorMsg);
                return;
            }
            int currentIndex = 0;
            if(dmCode.Substring(currentIndex,indexLen) != gtinTag)
            {
                HandleError(errorMsg);
                return ;
            }
            currentIndex += indexLen;
            currentIndex += gtinLen;
            if (dmCode.Substring(currentIndex, indexLen) != productionDateTag)
            {
                HandleError(errorMsg);
                return;
            }
            currentIndex += indexLen;
            string ProductionDate = dmCode.Substring(currentIndex, dateLen);
            currentIndex += dateLen ;
            if (dmCode.Substring(currentIndex, indexLen) != lotTag)
            {
                HandleError(errorMsg);
                return;
            }
            currentIndex += indexLen;
            string ProductionBatch = dmCode.Substring(currentIndex, lotLen);
            currentIndex += lotLen;
            if (dmCode.Substring(currentIndex, indexLen) != snTag)
            {
                HandleError(errorMsg);
                return;
            }

            var productionCode = ConfigurationManager.AppSettings["ProductionCode"]; //彩盒上产品代码
            

            AppendLog($"彩盒码: {dmCode} 格式校验成功", true);
            ApiLog.Debug($"彩盒码: {dmCode} 格式校验成功");
            dmText.BackColor = Color.LightGreen;
            try
            {
                var reportPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "reader_outerbox_label.frx");
                FastReport.Report report = new FastReport.Report();

                report.Load(reportPath);

                var model = new
                {
                    ProductionCode = productionCode,
                    ProductionBatch = ProductionBatch,
                    ProductionDate = ProductionDate,
                };


                //刷选可以打印字段特性的模型属性
                var list = model.GetType().GetProperties();
                //批量设置打印模板参数值
                foreach (PropertyInfo pro in list)
                {
                    var value = pro.GetValue(model, null);
                    //获取参数
                    FastReport.Data.Parameter param = report.Parameters.FindByName(pro.Name);
                    if (param != null)
                    {

                        param.Value = value; //将属性的值赋值给名字相同的报表参数
                    }
                }
                report.PrintSettings.Printer = "ZDesigner ZT510-300dpi ZPL"; // 设置默认打印机
                report.PrintSettings.ShowDialog = false; // 禁止显示打印对话框
                report.Prepare();
                if (checkViewPrint.Checked)
                {
                    report.ShowPrepared();
                }
                else
                {
                    // 直接打印报表
                    report.Print();
                }


                // 释放使用的资源
                report.Dispose();
            }
            catch (Exception ex)
            {
                HandleError(ex.Message);
            }

           
        }


        /// <summary>
        /// HandleError
        /// </summary>
        /// <param name="message"></param>
        private void HandleError(string message)
        {
            label2.Visible = true;
            label2.ForeColor = Color.Red;
            label2.Text = message;

            AppendLog($"彩盒码: {dmText.Text} {message}", false);
            ApiLog.Debug($"彩盒码: {dmText.Text} {message}");
            ResetDmText();

        }

        /// <summary>
        /// ResetDmText
        /// </summary>
        private void ResetDmText()
        {
            // 暂时禁用 TextChanged 事件处理程序
            dmText.TextChanged -= dmText_TextChanged;
            // 清空文本框并重置背景颜色
            dmText.Text = "";
            //dmText.BackColor = Color.White;

            // 重新启用 TextChanged 事件处理程序
            dmText.TextChanged += dmText_TextChanged;

            // 聚焦到 dmText
            dmText.Focus();
        }

        /// <summary>
        /// AppendLog
        /// </summary>
        /// <param name="message"></param>
        /// <param name="isError"></param>
        private void AppendLog(string message, bool isError)
        {
            // 选择文本颜色
            Color textColor = isError ? Color.Black : Color.Red;

            // 设置光标位置并插入文本
            logRichTextBox.SelectionStart = logRichTextBox.TextLength;
            logRichTextBox.SelectionLength = 0; // 取消任何选择

            logRichTextBox.SelectionColor = textColor; // 设置颜色
            logRichTextBox.AppendText(message + "\n"); // 添加文本
            logRichTextBox.SelectionColor = logRichTextBox.ForeColor; // 恢复默认颜色
            logRichTextBox.ScrollToCaret(); // 自动滚动到最后
        }

        /// <summary>
        /// 清空日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clearLogButton_Click(object sender, EventArgs e)
        {
            logRichTextBox.Clear();
        }
    }
}
